<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    svg{
      background-color: #eee;
    }
  </style>
</head>
<body>
  <svg width="400" height="400" >
    <path d="M200,250 L200,200 A50,50 0 0,1 250,250 Z"></path>
    <!-- Arx,ry 角度(只有当rxry不相等的时候才能起作用) 大小弧,顺时针或者逆时针 终点x,终点y-->
  </svg>

  <div id="box"></div>
</body>
</html>
<script>
  function getColor(){
    let r = Math.floor(Math.random()*256);
    let g = Math.floor(Math.random()*256);
    let b = Math.floor(Math.random()*256);
    return `rgb(${r},${g},${b})`
  }
  function chart(ele,data,option){
    let svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
    svg.setAttribute('width',option.width)
    svg.setAttribute('height',option.height)
    
    // 算出总和
    let total = data.reduce((prev,next)=>prev+next.value,0);
    // 根据比例算出弧度
    let ang = [];// 各个块的弧度
    for(let i = 0; i < data.length; i++){
      ang.push(data[i].value/total * 2 * Math.PI)
    }

    // 开始画弧
    let cx = option.width/2, cy = option.height/2;
    let r = option.width/2 - 10;
    let start = 0;;
    for(let i = 0; i < data.length;i++){
      let end = start + ang[i];// 当块的总弧度
      let x1 = cx + r * Math.sin(start);
      let y1 = cy - r * Math.cos(start);
      let x2 = cx + r * Math.sin(end);
      let y2 = cy - r * Math.cos(end);
      let path = document.createElementNS('http://www.w3.org/2000/svg','path');
      let d = `M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${ang[i] > Math.PI ? 1 : 0},1 ${x2},${y2} Z`;
      path.setAttribute('d',d);
      path.setAttribute('fill',getColor());
      svg.appendChild(path)
      let text = document.createElementNS('http://www.w3.org/2000/svg','text');
      text.innerHTML = data[i].name ;
      text.setAttribute('x',cx + r/2*Math.sin(start+ang[i]/2))
      text.setAttribute('y',cy - r/2*Math.cos(start+ang[i]/2))
      text.setAttribute('transform',`rotate(${(start+ang[i]/2 - Math.PI/2)*57} ${cx + r/2*Math.sin(start+ang[i]/2)},${cy - r/2*Math.cos(start+ang[i]/2)})`)
      svg.appendChild(text)
      
      start = end
    }


    ele.appendChild(svg);
  }
  var data = [
    {name:"css",value:20},
    {name:"js",value:30},
    {name:"html",value:10},
    {name:"vue",value:50},
    {name:"react",value:50}
    ]
  chart(document.getElementById('box'),data,{
    width:400,
    height:400
  });
</script>